package com.collins.thread.lock.cas;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class AtomIntegerTest {
    private static final int THREAD_CNT = 50;
    private static AtomicInteger aint = new AtomicInteger(0);
    private static CountDownLatch latch = new CountDownLatch(THREAD_CNT);
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        atomicIntegerTest();
    }

    public static void atomicIntegerTest() {
        int iter = 1000;
        for (int i = 0; i < THREAD_CNT; i++) {
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(20);
                    System.out.println(sdf.format(new Date(System.currentTimeMillis())) + "-"
                            + Thread.currentThread().getName() + " coming in...");
                    for (int j = 0; j < iter; j++) {
                        aint.getAndIncrement();
                    }
                    System.out.println(sdf.format(new Date(System.currentTimeMillis())) + "-"
                            + Thread.currentThread().getName() + " finished, now value: " + aint.get());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    latch.countDown();
                }
            }).start();
        }
        // TODO main thread waiting for all threads finished
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(sdf.format(new Date(System.currentTimeMillis())) + "-"
                + "total value: " + aint.get());
    }

    public static void checkReentrantLock() {
        ReentrantLock rlock = new ReentrantLock();
        rlock.lock();
    }
}
